package com.aabte.java8;

import org.testng.annotations.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Set;

public class TimeTest {

    @Test
    public void timeTest(){
        Clock clock = Clock.systemUTC();
        System.out.println(clock.instant());
        System.out.println(clock.millis());
        // 2019-02-17T04:33:18.115Z
        // 1550377998133

        LocalDate date = LocalDate.now();
        LocalDate dateFromClock = LocalDate.now(clock);
        System.out.println(date);
        System.out.println(dateFromClock);
        // 2019-02-17
        // 2019-02-17

        LocalTime time = LocalTime.now();
        LocalTime timeFromClock = LocalTime.now(clock);
        System.out.println(time);
        System.out.println(timeFromClock);
        // 12:33:18.146
        // 04:33:18.146

        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime dateTimeFromClock = LocalDateTime.now(clock);
        System.out.println(dateTime);
        System.out.println(dateTimeFromClock);
        // 2019-02-17T12:33:18.146
        // 2019-02-17T04:33:18.146


        /*
            计算两个时间的时间差
         */
        LocalDateTime from = LocalDateTime.of(2019, Month.APRIL, 16, 0, 0, 0);
        LocalDateTime to = LocalDateTime.of(2020, Month.APRIL, 16, 23, 59, 59);
        Duration duration = Duration.between(from, to);
        System.out.println("Duration in days: " + duration.toDays());
        System.out.println("Duration in hours: " + duration.toHours());
        // Duration in days: 366
        // Duration in hours: 8807

        /*
            时间格式化：DateTimeFormatter
         */
        DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
        LocalDateTime ldt = LocalDateTime.now();

        String strDate = ldt.format(dtf);
        System.out.println(strDate);

        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String strDate2 = dtf2.format(ldt);
        System.out.println(strDate2);

        LocalDateTime newDate = LocalDateTime.parse(strDate2, dtf2);
        System.out.println(newDate);

         /*
            对时区的操作ZonedDate/ZonedTime/ZonedDateTime
         */
        Set<String> set = ZoneId.getAvailableZoneIds();
        set.forEach(System.out::println);

        LocalDateTime ldt3 = LocalDateTime.now(ZoneId.of("Europe/Tallinn"));
        System.out.println(ldt3);

        LocalDateTime ldt4 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        ZonedDateTime zdt = ldt4.atZone(ZoneId.of("Asia/Shanghai"));
        System.out.println(zdt);
    }


}
